<?php
namespace app\store\controller\wxapp;
use app\store\controller\Controller;
use app\common\model\WxappPop as PopModel;

class Pop extends Controller{

    public function index(){
        $model = new PopModel;
        $list = $model->getList();
        return $this->fetch('index', compact('list'));
    }

    /**
     * 添加
     * @return array|mixed
     */
    public function add()
    {
        $model = new PopModel;
        if (!$this->request->isAjax()) {
            // 文章分类
            return $this->fetch('add');
        }
        $data=$this->postData('pop');

        if($this->getDefaultId() && $data['is_default']){
            return $this->renderError( '已有默认值');
        }

        // 新增记录
        if ($model->add($data)) {
            return $this->renderSuccess('添加成功', url('wxapp.pop/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    private function getDefaultId($id=0){
        $condition['is_default']=1;
        if($id){
            $condition['id']=$id;
        }
        $default_id=PopModel::where($condition)->value('id');
        return $default_id;
    }

    /**
     * 更新文章
     * @param $id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit($id)
    {
        // 详情
        $model = PopModel::detail($id);
        if (!$this->request->isAjax()) {
            // 文章分类
            return $this->fetch('edit', compact('model'));
        }
        $data=$this->postData('pop');

        if(!$this->getDefaultId($id) && $data['is_default']){
            return $this->renderError( '已有默认值');
        }

        // 更新记录
        if ($model->edit($data)) {
            return $this->renderSuccess('更新成功', url('wxapp.pop/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }
    /**
     * 删除
     * @param $id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete($id)
    {

        $model = PopModel::detail($id);
        if (!$model->delete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }
}